import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket  = null;
    //因为UDP不会保存对端的信息，所以需要将应用程序里将对端的信息记录下来
    //主要记录对端的ip地址以及端口号
    private  String serverip = "";
    private  int serverport = 0;

    public UdpEchoClient(String ip,int port) throws SocketException {
        this.socket = new DatagramSocket();
        this.serverip = ip;
        this.serverport = port;
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("客户端启动");
        while (true) {
            //1.从键盘接收数据并打包成数据报
            System.out.println("->");
            String request = scanner.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    //将字符串进行处理为地址
                    InetAddress.getByName(serverip),serverport);
            //2.发送给服务器
            socket.send(requestPacket);
            //3.接收并解析服务器返回的响应
            DatagramPacket responcePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responcePacket);
            String responce = new String(responcePacket.getData(),0,responcePacket.getLength());
            System.out.println(responce);
        }
    }

    public static void main(String[] args) throws IOException {
        //手动输入服务器的地址以及端口号
        UdpEchoClient client = new UdpEchoClient("192.168.3.184",9090);
        client.start();
    }
}
